/**
 * 数据库初始化脚本
 * 用于初始化数据库表和数据
 */
const sequelize = require('../config/database')
const { User, Category, Bill } = require('../models')
const bcrypt = require('bcryptjs')

// 加载环境变量 - 先加载默认配置
require('dotenv').config()

// 确保 NODE_ENV 没有多余空格并转换为小写进行比较
const nodeEnv = (process.env.NODE_ENV || 'development').trim().toLowerCase()

// 再根据处理后的 NODE_ENV 加载特定环境的配置
const envPath = `.env.${nodeEnv}`
require('dotenv').config({ path: envPath })

console.log('当前是:', nodeEnv === 'production' ? '生产环境' : '开发环境')

// 从环境变量中获取超级管理员配置
const superAdminName = process.env.SUPER_ADMIN_NAME
const superAdminPassword = process.env.SUPER_ADMIN_PASSWORD
/**
 * 初始化数据库
 */
async function initDatabase() {
	try {
		// 同步数据库模型（创建表）
		await sequelize.sync({ force: true })
		console.log('数据库表创建成功')

		// 禁用外键约束
		await sequelize.query('SET FOREIGN_KEY_CHECKS = 0;')
		console.log('外键约束已禁用')

		// 强制删除并重新创建所有表
		// 使用{ force: true }确保表结构被完全重建
		console.log('开始创建表结构...')
		await sequelize.sync({ force: true })
		console.log('数据库表强制创建成功')

		// 验证表是否存在
		const tables = ['users', 'categories', 'bills']
		for (const table of tables) {
			try {
				const result = await sequelize.query(`SHOW TABLES LIKE '${table}'`)
				console.log(`表 ${table} 存在:`, result[0].length > 0)
			} catch (error) {
				console.error(`检查表 ${table} 存在性失败:`, error)
			}
		}

		// 启用外键约束
		await sequelize.query('SET FOREIGN_KEY_CHECKS = 1;')
		console.log('外键约束已启用')

		// 创建默认用户

		const hashedPassword = await bcrypt.hash(superAdminPassword, 10)

		await User.create({
			username: superAdminName,
			password: hashedPassword,
			phone: '13911111111',
			register_time: new Date(),
			role: 'super'
		})

		console.log('管理员用户创建成功，')

		// 创建默认分类
		const defaultCategories = [
			// 支出分类
			{ name: '餐饮', icon: '../../static/icons/foot.png', bg_class: 'bg-red-500', create_time: new Date() },
			{ name: '购物', icon: '../../static/icons/shopping.png', bg_class: 'bg-pink-500', create_time: new Date() },
			{ name: '交通', icon: '../../static/icons/cart.png', bg_class: 'bg-cyan-500', create_time: new Date() },
			{
				name: '住房',
				icon: '../../static/icons/house.png',
				bg_class: 'bg-cyan-500',
				create_time: new Date()
			},
			{ name: '娱乐', icon: '../../static/icons/play.png', bg_class: 'bg-amber-500', create_time: new Date() },
			{ name: '医疗', icon: '../../static/icons/yiliao.png', bg_class: 'bg-rose-500', create_time: new Date() },
			{ name: '教育', icon: '../../static/icons/book.png', bg_class: 'bg-teal-500', create_time: new Date() },
			// 收入分类
			{ name: '工资', icon: '../../static/icons/salary.png', bg_class: 'bg-blue-500', create_time: new Date() },
			{ name: '其他', icon: '../../static/icons/other.png', bg_class: 'bg-indigo-500', create_time: new Date() }
		]

		await Category.bulkCreate(defaultCategories)
		console.log('默认分类创建成功')

		// 创建示例账单数据
		const userId = 1 // 默认用户ID
		const currentDate = new Date()
		const currentYear = currentDate.getFullYear()
		const currentMonth = currentDate.getMonth()

		const sampleBills = [
			// 本月收入
			{
				user_id: userId,
				category_id: 1, // 工资
				amount: 8000,
				type: 'income', // 收入
				remark: '本月工资',
				bill_date: new Date(currentYear, currentMonth, 5, 10, 30),
				create_time: new Date()
			},
			{
				user_id: userId,
				category_id: 2, // 奖金
				amount: 2000,
				type: 'income', // 收入
				remark: '季度奖金',
				bill_date: new Date(currentYear, currentMonth, 10, 14, 15),
				create_time: new Date()
			},

			// 本月支出
			{
				user_id: userId,
				category_id: 6, // 餐饮
				amount: 1200,
				type: 'expense', // 支出
				remark: '本月餐饮费',
				bill_date: new Date(currentYear, currentMonth, 15, 12, 0),
				create_time: new Date()
			},
			{
				user_id: userId,
				category_id: 7, // 购物
				amount: 1500,
				type: 'expense', // 支出
				remark: '购买衣物',
				bill_date: new Date(currentYear, currentMonth, 18, 16, 45),
				create_time: new Date()
			},
			{
				user_id: userId,
				category_id: 8, // 交通
				amount: 500,
				type: 'expense', // 支出
				remark: '交通费',
				bill_date: new Date(currentYear, currentMonth, 20, 9, 15),
				create_time: new Date()
			},

			// 上月数据
			{
				user_id: userId,
				category_id: 1, // 工资
				amount: 8000,
				type: 'income', // 收入
				remark: '上月工资',
				bill_date: new Date(currentYear, currentMonth - 1, 5, 10, 30),
				create_time: new Date(currentYear, currentMonth - 1, 5, 10, 30)
			},
			{
				user_id: userId,
				category_id: 6, // 餐饮
				amount: 1100,
				type: 'expense', // 支出
				remark: '上月餐饮费',
				bill_date: new Date(currentYear, currentMonth - 1, 15, 12, 0),
				create_time: new Date(currentYear, currentMonth - 1, 15, 12, 0)
			}
		]

		await Bill.bulkCreate(sampleBills)
		console.log('示例账单数据创建成功')

		console.log('数据库初始化完成')
	} catch (error) {
		console.error('数据库初始化失败:', error)
	} finally {
		// 关闭数据库连接
		await sequelize.close()
	}
}

// 执行初始化
initDatabase()
